import Router from 'koa-router';
import getAppInfo from '../apps_info'
import shell from 'shelljs'

const router = Router()

router.post('/', async (ctx, next) => {
  ctx.status = 200;
  ctx.body = `${new Date()}\nIt's a nice day, isn't it?`
  try {
    // use appname as secret
    const appName = ctx.request.body.secret;
    // get app info
    const appInfo = getAppInfo(appName)
    if(appInfo){
      ctx.log.info(appInfo);
      ctx.body = appName;
      // run shell
      // appInfo.shell like: cd /apps && git pull && dosth
      shell.exec(appInfo.shell)
    }
  } catch (e) {
    ctx.log.error(e)
  }

  next();
});

export default router;